package com.tanhua.server.interceptor;

import com.alibaba.fastjson.JSON;
import com.tanhua.manage.domain.db.User;
import com.tanhua.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    /**
     * 在进入controller方法前执行
     * 从请求头中获取token，根据token从redis中获取用户信息，如果能得到信息就存入线程，放行；
     * 如果得不到就返回401，阻止请求
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("请求的路径：" + request.getRequestURI());
        String token = request.getHeader("Authorization");
        log.debug(token);
        if (StringUtils.isNotEmpty(token)){
            User user = getUserByToken(token );
            if (null != user){
                UserHolder.setUser(user);
                return true;
            }
        }
        response.setStatus(401);
        return false;
    }
    /**
     * 通过token获取登陆用户信息
     * @param token
     * @return
     */
    public User getUserByToken(String token){
        //通过token从redis中获取登录用户的信息
        String tokenKey = "TOKEN_" + token;
        String userJsonStr = (String) redisTemplate.opsForValue().get(tokenKey);

        //用户长时间未登录，token会失效,如果token获取不到用户名，返回null
        if (null == userJsonStr){
            return null;
        }
        //不为空，登录成功，延长token有效期
        redisTemplate.expire(tokenKey,7, TimeUnit.DAYS);
        //获取到user信息，返回
        User user = JSON.parseObject(userJsonStr, User.class);
        return user;
    }
}
